#include "Writer.h"

Writer::Writer()
{}

Writer::Writer(string _filename)
{
	filename = _filename;

	fstream fileStr;
	fileStr.open(filename, fstream::in);
	fileStr << "";
	fileStr.close();
}

bool Writer::write(vector<Task> taskList)
{
	try
	{
		ofstream file;
		file.open (filename, fstream::trunc);
	
		for(unsigned int i=0; i<taskList.size(); i++)
		{
			file << convertInt(taskList[i].getTaskID()) << endl;
			file << taskList[i].getTaskName() << endl;
			file << boolalpha << taskList[i].getDone() << endl;
			file << convertInt(taskList[i].getTaskType()) << endl;
			file << convertInt(taskList[i].getPriority()) << endl;
			file << to_simple_string(taskList[i].getStartDateTime()) << endl;
			file << to_simple_string(taskList[i].getEndDateTime()) << endl;
		}

		file.close();
		return true;
	}
	catch(...)
	{
		return false;
	}
}

string Writer::convertInt(int number)
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}

bool Writer::read(vector<Task>& taskList)
{

	ifstream file (filename);
	if (file.is_open())
	{
		parseData(file, taskList);

		file.close();
		return true;
	}
	else
		return false;
}

void Writer::parseData(ifstream& file, vector<Task>& taskList)
{
	string line;

	while (file.good())
	{
		Task task;

		getline(file,line);

		if(line == "")
			break;
		task.setTaskID(atoi(line.c_str()));

		getline(file, line);
		task.setTaskName(line);

		getline(file, line);
		task.setDone(convertToBool(line));

		getline(file, line);
		task.setTaskType(convertToTaskType(line));

		getline(file, line);
		task.setPriority(atoi(line.c_str()));

		getline(file, line);
		if(line != "not-a-date-time")
			task.setStartDateTime(time_from_string(line));

		getline(file, line);
		if(line != "not-a-date-time")
			task.setEndDateTime(time_from_string(line));

		taskList.push_back(task);
	}
}

bool Writer::convertToBool(string line)
{
	if(line == "true")
		return true;
	else
		return false;
}

Task::TaskType Writer::convertToTaskType(string line)
{
	if(line == "1")
		return Task::FLOATING;
	else if(line == "2")
		return Task::DEADLINE;
	else 
		return Task::TIMED;
}